const Hook = require('./hook')

/**
 * 钩子 --- 代码工厂，提供模板
*/
class SyncHookCodeFactory {
  // constructor() {
  //   this.option = {}
  // }

  setup(hook, options) {
    hook._x = options.taps.map(item => item.fn)
  }

  create(options) {
    const fn = new Function(
      options.ages,
      `
        ${this.head()}
        ${this.content(options)}
      `
    )

    return fn
  }

  head() {
    return  `
      "use strict";
      var _context;
      var _x = this._x;
    `
  }
  content(options) {
    let ages = options.ages.join(',')
    let code = ''
    const len = options.taps.length

    for (let i = 0; i < len; i++) {
      code += `
        var _fn${i} = _x[${i}];
        _fn${i}(${ages});
      `
    }

    return code
  }
}

const factory = new SyncHookCodeFactory()


function SyncHook(ages) {
  const hook = new Hook(ages)

  // 设置钩子的编译器
  hook.compiler = function(options) {
    factory.setup(this, options)
    return factory.create(options)
  }
  return hook
}

module.exports = SyncHook